package com.ds.robot.assistant.job;

import com.ds.robot.assistant.enums.Env;
import com.ds.robot.assistant.service.HolidayServiceContext;
import com.ds.robot.assistant.util.DateUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;
import java.util.Map;

/**
 * 作用：给公司张会玲用
 *
 * @author WeiShaoying
 * 
 */
@Service
@Slf4j
public class SeniorTipJob {

    private static final DateTimeFormatter FORMATTER = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

    private final RestTemplate restTemplate;

    @Autowired
    private HolidayServiceContext holidayServiceContext;

    @Autowired
    public SeniorTipJob(RestTemplateBuilder restTemplateBuilder) {
        this.restTemplate = restTemplateBuilder.build();
    }


    @Scheduled(cron = "0 0 14,16 ? * SAT")
    public void dutyTip() {
        log.info("==== 公司高管群定时任务开始：" + FORMATTER.format(LocalDateTime.now()));

        boolean firstSaturdayOfMonth = DateUtil.isFirstSaturdayOfMonth(LocalDate.now());
        if (firstSaturdayOfMonth) {
            log.info("今天是本月的第一个周六，不发提醒");
            return;
        }
        if (holidayServiceContext.isHoliday(LocalDate.now().toString())) {
            log.info("今天是法定节假日，不发提醒");
            return;
        }
        log.info("今天是普通周六，发提醒");
        String message = buildMessage();
        sendTipMessage(message, Env.TEST);
        sendTipMessage(message, Env.PROD);

        log.info("==== 公司高管群定时任务完成：" + FORMATTER.format(LocalDateTime.now()));
    }

    private String buildMessage() {
        return "# 温馨提示\n" +
                "请您尽快完成<font color=\"warning\">**个人及部门的周工作总结与计划**</font>并于今日发送至总部高管沟通群内！@所有人"
                ;
    }


    // 发送提醒
    private void sendTipMessage(String message, Env env) {
        // 构建消息体
        Map<String, Object> requestBody = new HashMap<>();
        requestBody.put("msgtype", "markdown");
        Map<String, Object> markdown = new HashMap<>();
        markdown.put("content", message);
        markdown.put("mentioned_list", new String[]{"@all"});
        markdown.put("mentioned_mobile_list", new String[]{"@all"});
        requestBody.put("markdown", markdown);

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.APPLICATION_JSON);

        HttpEntity<Map<String, Object>> entity = new HttpEntity<>(requestBody, headers);

        try {
            // 发送POST请求
            String webHookUrl = env.equals(Env.PROD) ?
                    "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=06645b73-9903-47b8-a3d7-79e43264af86" :
                    "https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=54b611ad-75a0-4e53-b84c-da3903833946";
            ResponseEntity<String> response = restTemplate.postForEntity(webHookUrl, entity, String.class);

            if (!response.getStatusCode().is2xxSuccessful()) {
                throw new RuntimeException("Failed to send message. HTTP status code: " + response.getStatusCode());
            }
            log.info("Message sent successfully.");
        } catch (Exception e) {
            log.error("Error sending message: " + e.getMessage());
        }
    }
}
